package com.littlerpc.protocol.net.netty.server;

import com.littlerpc.protocol.codec.Serializer;
import com.littlerpc.protocol.net.common.*;
import com.littlerpc.protocol.net.netty.codec.NettyDecoder;
import com.littlerpc.protocol.net.netty.codec.NettyEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Setter;

/**
 *
 * @author ChengPeng
 * @date 2017/6/15
 * rpc服务
 */
@Setter
public class NettyServer extends RpcServer {

    private String host = "rpc.server";

    public NettyServer(int port, Serializer serializer) {
        super(port, serializer);
    }

    @Override
    public void start() {

        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup work = new NioEventLoopGroup(4);

        ServerBootstrap server = new ServerBootstrap();
        server.group(boss, work)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast("decoder", new NettyDecoder(serializer, RpcRequest.class))
                                .addLast("encoder", new NettyEncoder(serializer, RpcResponse.class))
                                .addLast(new NettyServerHandler());
                    }
                })
                .option(ChannelOption.SO_TIMEOUT, 100)
                .option(ChannelOption.SO_BACKLOG, 128)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_REUSEADDR, true)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        try {
            ChannelFuture future =  server.bind(port/*new InetSocketAddress(host, port)*/).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            work.shutdownGracefully();
            boss.shutdownGracefully();
        }

    }

    @Override
    public void stop() {
        //TODO 停止服务
    }
}
